package com.fast.cron.db.service;

import com.fast.cron.db.RowMapper;
import com.fast.cron.db.dao.AbstractDao;
import com.fast.cron.db.dao.EventsDao;
import com.fast.cron.db.entry.Events;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: Leo Jie
 * @date: 2018-10-04 21:10
 * @version: v1.0
 */
public class EventsService extends AbstractDao implements EventsDao {
    @Override
    public long recordEvent(Events event) throws SQLException {
        String sql = "insert into fast_cron_events (event_type, event_time, username, message)\n" +
                "values (?, ?, ?, ?)";
        return insert(sql, event.getEventType(), event.getEventTime(),
                event.getUsername(), event.getMessage());
    }

    @Override
    public List<Events> listEvents() throws SQLException {
        String sql = "select\n" +
                "  event_id,\n" +
                "  event_type,\n" +
                "  event_time,\n" +
                "  username,\n" +
                "  message\n" +
                "from fast_cron_events;";
        return query(Events.class, sql, new EventsRowMapper().rowMapperMap());
    }

    private class EventsRowMapper implements RowMapper {
        @Override
        public Map rowMapperMap() {
            Map<String, String> rowMap = new HashMap<>(3);
            rowMap.put("event_id", "eventId");
            rowMap.put("event_type", "eventType");
            rowMap.put("event_time", "eventTime");
            return rowMap;
        }
    }
}